<?php

use \GatewayWorker\Lib\Gateway;
class Events
{
    // 当有客户端连接时，将client_id返回，让mvc框架判断当前uid并执行绑定
    public static function onConnect($client_id)
    {

            $num=Gateway::getAllClientIdCount();    //当前在线人数
         
            $message=[
                "people_num"=>$num,
                 "type"=>"getNum"
            ];

            Gateway::sendToAll(json_encode($message));

            Gateway::sendToClient($client_id, json_encode(array(    //并且发送当前用户的id
                "client_id"=>$client_id,
                 "type"=>"init"
            )));    

        
    }

    // GatewayWorker建议不做任何业务逻辑，onMessage留空即可
    public static function onMessage($client_id, $message)
    {
        
    }


       public static function onClose($client_id)   //当用户退出时,也发送当前平台人数
    {       
           $num=Gateway::getAllClientIdCount();    //当前在线人数


           $message=[
                    "people_num"=>$num,
                     "type"=>"getNum"
                ];

           Gateway::sendToAll(json_encode($message));

           //通知聊天室中的另外一个人对方已经掉线

           $arr=Gateway::getAllClientSessions();    //当前用户

           foreach ($arr as $key => $value) {

               if($value['he_or_she_id']==$client_id){

                  $he_or_she_name=$value['he_or_she_name'];

                  $send_user_id=$key;

                  break;
               }

           }

           $message=[
            "type"=>"exit",
            "he_or_she_name"=>$he_or_she_name,
            "exit_client_id"=>$client_id
           ];

            Gateway::sendToClient($send_user_id,json_encode($message));


    }
}
